package com.tenebrous.jestic.controller.framwork.acom;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tenebrous.jestic.controller.SupperController;
import com.rain.ops.sdk.utils.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;

/**
 * 表格导出
 */
@Validated
@RestController
@RequestMapping("/common/eltable")
public class EltableController extends SupperController {

    /**
     * 导出excel 包含表头
     *
     * @param data
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/excel/export")
    public void exportExcel(String data, HttpServletResponse response) throws Exception {

        JSONObject jobject = JSONObject.parseObject(data);
        JSONArray columns = jobject.getJSONArray("columns");
        JSONArray rows = jobject.getJSONArray("rows");

        // 生成一个表格
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("Sheet1");

        // 创建表头
        int rownum = 0;
        HSSFRow row = sheet.createRow(rownum++);
        for (int i = 0; i < columns.size(); i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(columns.getString(i));
        }
        // 创建内容
        for (int i = 0; i < rows.size(); i++) {
            JSONArray rowdata = rows.getJSONArray(i);
            row = sheet.createRow(rownum++);
            for (int j = 0; j < rowdata.size(); j++) {
                row.createCell(j).setCellValue(rowdata.getString(j));
            }
        }
        File folder = new File(super.getRealPath("download"));
        String filename = String.format("%s.xls", DateUtils.getTimeMillis() + "");
        File dfile = new File(folder, filename);
        File pfile = dfile.getParentFile();
        if(!pfile.exists()) {
            pfile.mkdirs();
        }

        FileOutputStream out = new FileOutputStream(dfile);
        wb.write(out);
        out.flush();
        out.close();

    }
}
